<template>
  <view class="start-page">
    <view class="info-block">
      <view class="info-item">
        <text class="label">店铺名称：</text>
        <text class="value">{{ shopName }}</text>
      </view>

      <view class="info-item">
        <text class="label">桌号：</text>
        <text class="value">{{ tableNumber }}</text>
      </view>

      <view class="info-item">
        <text class="label">台球类型：</text>
        <text class="value">{{ type }}</text>
      </view>

      <view class="info-item">
        <text class="label">价格：</text>
        <text class="value">¥{{ price }} / 分钟</text>
      </view>
    </view>

    <!-- 新增模块 -->
    <view class="action-block" v-for="(item, index) in actionItems" :key="index">
      <!-- 左侧文字区域 -->
      <view class="action-text">
        <view class="action-title">{{ item.title }}</view>
        <view class="action-description">{{ item.description }}</view>
        <view class="action-icons" v-if="item.icons">
          <image v-for="(icon, idx) in item.icons" :key="idx" :src="icon" class="action-icon"></image>
        </view>
      </view>
      <!-- 右侧按钮 -->
      <button class="action-button" @click="handleAction(item.action)">去开台</button>
    </view>

    <Dialog
        :title="dialogTitle"
        :visible="dialogVisible"
        :confirmButtonText="confirmButtonText"
        :cancelButtonText="cancelButtonText"
        @confirm="onConfirm"
        @cancel="onCancel"
        @update:visible="dialogVisible = $event"
    >
      <view class="dialog-content">
        <view class="dialog-section">
          <view class="value-container">
            <text class="dialog-label">计费价格</text>
            <text class="dialog-value">按分钟收费，不足1分钟按1分钟收费，最低消费0元</text>
          </view>

          <view class="dialog-price">
            <text>¥28/小时</text>
          </view>
        </view>

        <view class="dialog-section">
          <view class="value-container">
            <text class="dialog-label">押金</text>
            <text class="dialog-value">结束即退押金</text>
          </view>

          <view class="dialog-price">
            <text>¥60</text>
          </view>
        </view>

        <view class="dialog-section">
          <view class="value-container">
            <text class="dialog-label">优惠券</text>
            <text class="dialog-value">优惠券在结算时抵扣</text>
          </view>

          <view class="dialog-price">
            <text>1张可选</text>
          </view>

        </view>
        <view class="dialog-section">
          <text class="dialog-label">支付方式</text>
          <text class="dialog-value">微信支付</text>
        </view>
        <view class="dialog-agreement">
          <checkbox value="agree" checked />
          <text>开台视为已阅读并同意《用户授权协议》及《充值协议》</text>
        </view>
      </view>
    </Dialog>


  </view>
</template>

<script>
import Dialog from './Dialog.vue';

export default {
  components: {
    Dialog
  },
  data() {
    return {
      tableNumber: '',
      shopName: '',
      type: '',
      price: '',

      dialogTitle: '自助开台',
      dialogVisible: false,
      confirmButtonText: '立即开台',
      cancelButtonText: '取消',


      actionItems: [
        {
          title: '自助开台',
          description: '使用会员或押金开台',
          icons: [], // 可选，这里为空
          action: 'selfStart'
        },
        {
          title: '团购券开台',
          description: '使用美团、抖音等团购券开台',
          icons: [
            '/static/img/meituan.png', // 示例图标路径
            '/static/img/douyin.png',
            '/static/img/dazhongdianping.png'
          ],
          action: 'grouponStart'
        },
        {
          title: '约球开台',
          description: '邀约好友一起玩',
          icons: [],
          action: 'inviteStart'
        }
      ]
    };
  },
  onLoad(options) {
    this.tableNumber = options.tableNumber;
    this.shopName = options.shopName;
    this.type = options.type;
    this.price = parseFloat(options.price) || 0; //强制转成 number 类型
    this.startTime = options.startTime; // 新增：接收来自 shop.vue 的开始时间
  },
  methods: {
    handleAction(actionType) {
      switch (actionType) {
        case 'selfStart':
          this.dialogVisible = true; // 点击“自助开台”时显示弹窗
          break;
        case 'grouponStart':
          console.log('执行团购券开台逻辑');
          break;
        case 'inviteStart':
          console.log('执行约球开台逻辑');
          break;
        default:
          console.log('未知操作类型');
      }
    },
    selfStart() {
      this.dialogVisible = true;
    },
    onConfirm() {
      const now = new Date();
      const orderId = this.formatOrderIdTime(now) + String(Math.floor(Math.random() * 90 + 10)); // 如：20240621153087

      // 示例：假设默认订单生成时不设置 endTime
      const orderData = {
        orderId,
        shopName: this.shopName,
        tableNumber: this.tableNumber,
        startTime: this.startTime, // 使用从 shop.vue 传进来的开始时间
        createdTime: now.toLocaleString(),
        status: 'processing',
        duration: null, // 初始化为空
        price: parseFloat(this.price) // 保存价格
      };

      // 使用数组保存订单
      let ordersList = uni.getStorageSync('ordersList') || [];

      // 检查是否已存在相同订单
      if (!ordersList.some(order => order.orderId === orderData.orderId)) {
        ordersList.push(orderData);
        uni.setStorageSync('ordersList', ordersList);
      }

      // 记录当前桌号为“已占用”
      let occupiedTables = uni.getStorageSync('occupiedTables') || [];
      if (!occupiedTables.includes(this.tableNumber)) {
        occupiedTables.push(this.tableNumber);
        uni.setStorageSync('occupiedTables', occupiedTables);
      }

      // 启动定时器，4小时后自动结算
      setTimeout(() => {
        this.autoSettleOrder(orderData);
      }, 4 * 60 * 60 * 1000); // 4小时

      uni.$emit('updateOccupiedTables');

      // 跳转到 tabbar-4 页面
      uni.switchTab({
        url: '/pages/tabbar/tabbar-4/tabbar-4'
      });
    },
    onCancel() {
      console.log('取消开台');
      this.dialogVisible = false;
    },
    formatOrderIdTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}${month}${day}${hours}${minutes}`;
    },
    autoSettleOrder(order) {
      const now = new Date().getTime();
      const diffMs = Math.max(0, now - order.startTime);
      const minutes = 4 * 60; // 固定按4小时计算

      // 计算总价：价格 * 分钟数
      const totalPrice = (order.price * minutes).toFixed(2);
      // 更新订单状态、结束时间和计时时长
      const updatedOrder = {
        ...order,
        endTime: now,
        duration: this.formatDuration(order.startTime, now),
        totalPrice,
        status: 'pendingPayment',
        isAutoSettled: true
      };
      // 保存更新后的订单列表
      let ordersList = uni.getStorageSync('ordersList') || [];
      const targetIndex = ordersList.findIndex(o => o.orderId === updatedOrder.orderId);
      if (targetIndex > -1) {
        ordersList.splice(targetIndex, 1, updatedOrder);
      } else {
        ordersList.push(updatedOrder);
      }
      uni.setStorageSync('ordersList', ordersList);
      // 移除球桌占用状态
      let occupiedTables = uni.getStorageSync('occupiedTables') || [];
      if (updatedOrder.tableNumber && occupiedTables.includes(updatedOrder.tableNumber)) {
        occupiedTables = occupiedTables.filter(num => num !== updatedOrder.tableNumber);
        uni.setStorageSync('occupiedTables', occupiedTables);
      }
    }
  }
};
</script>

<style>

pages {
  background-color: #f0d04e;
}

.start-page {
  padding: 40rpx;
  background-color: #f0d04e;
  min-height: 100vh; /* 改成 100vh 保证撑满屏幕 */
  box-sizing: border-box; /* 确保 padding 不会影响高度计算 */
}

.info-block {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.label {
  font-weight: bold;
  width: 160rpx;
  font-size: 32rpx;
  color: #666;
}

.value {
  font-size: 32rpx;
  color: #333;
}

.action-block {
  background-color: #fdf5e6;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-top: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative; /* 添加相对定位 */
}


.action-text {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.action-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.action-description {
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
}


.action-icons {
  display: flex;
  margin-bottom: 20rpx;
}

.action-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 15rpx;
  margin-top: 15rpx;

}

.action-button {
  width: 180rpx; /* 固定宽度 */
  background-color: #ffc107;
  color: #000;
  font-size: 32rpx;
  border-radius: 40rpx;
  padding: 10rpx 20rpx;
  border: 5rpx solid #000;
  text-align: center;
  position: absolute; /* 使用绝对定位 */
  right: 30rpx; /* 根据 .action-block 的 padding 设置相同的值 */
  top: 50%; /* 垂直居中 */
  transform: translateY(-50%); /* 微调垂直居中效果 */
}

.dialog-content {
  padding: 20px;
  text-align: left;
}

.dialog-section {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 20px;
  width: 100%;
}

.value-container {
  flex: 3;
  width: 70%;
  display: flex;
  flex-direction: column;
}

.dialog-price {
  flex: 2;
  width: 30%;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  text-align: right;
}

.dialog-label {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.dialog-value {
  font-size: 14px;
  font-weight: bold;
  color: #666;
}

.dialog-agreement {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

.dialog-agreement checkbox {
  margin-right: 5px;
}
</style>